import { Suspense } from "react";
import {
  createBrowserRouter,
  createHashRouter,
  RouteObject,
} from "react-router-dom";
import { appConfig, routes } from "./config";
import AuthGuard from "./AuthGuard";
import { RouteConfig } from "./types";

/**
 * 将我们的路由配置转换为React Router的RouteObject
 */
function generateRouteObjects(
  routes: RouteConfig[],
  parentPath = ""
): RouteObject[] {
  return routes.map((route) => {
    // 构建完整路径
    const path = `${parentPath}/${route.path}`.replace(/\/+/g, "/");
    // 修复：始终使用相对路径，不要对布局组件特殊处理
    const relativePath = route.path === "*" ? "*" : route.path;

    // 路由对象结构
    const routeObject: RouteObject = {
      // 修复：为所有路由都设置路径，包括布局路由
      path: relativePath,
    };

    // 如果是布局组件，直接使用React元素
    if (route.isLayout && route.component) {
      const LayoutComponent = route.component;

      routeObject.element = (
        <Suspense fallback={route.fallback || <div>加载中...</div>}>
          <LayoutComponent routes={routes} />
        </Suspense>
      );
    }
    // 如果是普通组件，使用AuthGuard包装
    else if (route.component) {
      // 修复：确保正确使用AuthGuard
      const RouteComponent = route.component;
      routeObject.element = (
        <AuthGuard route={route}>
          <Suspense fallback={route.fallback || <div>加载中...</div>}>
            <RouteComponent />
          </Suspense>
        </AuthGuard>
      );
    }

    // 添加错误元素
    if (route.errorElement) {
      routeObject.errorElement = route.errorElement;
    }

    // 递归处理子路由
    if (route.children && route.children.length > 0) {
      routeObject.children = generateRouteObjects(route.children, path);
    }

    return routeObject;
  });
}

/**
 * 创建路由器
 */
const createRouter = () => {
  const routeObjects = generateRouteObjects(routes);

  // 调试输出
  console.log("Generated route objects:", routeObjects);

  // 根据配置决定使用哪种路由模式
  return appConfig.routeMode === "hash"
    ? createHashRouter(routeObjects)
    : createBrowserRouter(routeObjects, {
        // Remove unsupported future config or update to supported properties
        // based on your React Router version
      });
};

export const router = createRouter();
export default router;
